package com.oumiao.echarts.service;

import cn.hutool.json.JSONUtil;
import com.oumiao.echarts.config.SocketVO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("sse")
public class SSEService {

    @GetMapping("test")
    public SseEmitter test(){
        SseEmitter emitter = new SseEmitter();
        SocketVO<String> socketVO = new SocketVO<>();
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            list.add(i+"aaaaaaaaa");
        }
        String jsonStr = JSONUtil.toJsonStr(list);
        socketVO.setTime(new Date());
        socketVO.setData(jsonStr);
        socketVO.setType("test");
        String jsonStr1 = JSONUtil.toJsonStr(socketVO);
        // 异步发送事件以避免阻塞主线程
        new Thread(() -> {
            try {
                while (true) { // 或者根据实际情况调整循环条件
                    emitter.send(SseEmitter.event()
                            .name("message") // 事件名称
                            .data(jsonStr1)); // 数据
                }
            } catch (IOException e) {
                emitter.completeWithError(e);
            }
        }).start();
        return emitter;
    }
}
